package com.firebugsoft.metadata.api.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.csource.fastdfs.UploadStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.firebugsoft.common.mvc.json.Body;

@Controller
@RequestMapping(value = { "/upload" })
public class UploadController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value(value = "${local.domain}")
    private String localDomain;
    @Resource
    private TrackerClient trackerClient;

    @PostConstruct
    void init() throws FileNotFoundException, IOException, MyException {
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        ClientGlobal.init(classPath + "fastdfs-client.properties");
        trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        trackerServer.close();
    }
    
    @ResponseBody
    @RequestMapping(value = { "/temporary" }, method = { RequestMethod.POST })
    public Body temporary(HttpServletRequest request, @RequestParam MultipartFile file) throws IOException {
        String realPath = request.getSession().getServletContext().getRealPath("/temporary");
        String filename = System.currentTimeMillis() + "." + StringUtils.getFilenameExtension(file.getOriginalFilename());
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, filename));
        return Body.newInstance(localDomain + request.getContextPath() + "/temporary/" + filename);
    }

    @ResponseBody
    @RequestMapping(value = { "/fastdfs" }, method = { RequestMethod.POST })
    public Body fastdfs(@RequestParam MultipartFile[] files) throws IOException, MyException {
        List<String> fileIds = new ArrayList<String>(files.length);
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getConnection();
            StorageClient1 client = new StorageClient1(trackerServer, null);
            for (MultipartFile file : files) {
                String ext = StringUtils.getFilenameExtension(file.getOriginalFilename());
                UploadStream stream = new UploadStream(file.getInputStream(), file.getSize());
                String fileId = client.upload_file1(null, file.getSize(), stream, ext, null);
                logger.info("fastdfs save success: " + fileId);
                fileIds.add(fileId);
            }
        } catch (IOException | MyException e) {
            logger.error("fastdfs save failure: ", e);
            throw e;
        } finally {
            if (trackerServer != null) {
                trackerServer.close();
            }
        }
        return Body.newInstance(fileIds);
    }
}
